# Copyright (c) 2023 az13js
# 基金分类/classify-funds is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of
# the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#          http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF
# ANY KIND,EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
# NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.

import os
import re
import csv
from datetime import date
from pathlib import Path
import openpyxl

def build_csv_file(dir_name):
    """
    参数：
        dir_name 分析报告保存在此目录内。
    返回值：
        无
    """
    dir_number = 0
    datas = {} # Key是基金代码，Value是基金出现的次数。分析的基金必须在所有数据目录内都跟踪到。
    ts = {}
    pattern = re.compile(r"\d{4}-\d{2}-\d{2}")
    fund_xlsx_pattern = re.compile(r"\d+\.xlsx")
    for entry in os.scandir():
        if entry.is_dir() and re.match(pattern, entry.name):
            dir_number = dir_number + 1
            for fund in os.scandir(entry.name):
                if re.match(fund_xlsx_pattern, fund.name):
                    fund_code = fund.name.split('.', 1)[0]
                    if fund_code not in datas:
                        datas[fund_code] = 1
                    else:
                        datas[fund_code] = datas[fund_code] + 1
    full_new_datas = {}
    for fund_code in datas.keys():
        # 基金代码在所有采集到的数据中都存在，那么就有足够的数据分析它。
        if datas[fund_code] == dir_number:
            print(fund_code)
            for entry in os.scandir():
                if entry.is_dir() and re.match(pattern, entry.name):
                    number_of_shares = None
                    date_time = None
                    average_nav = None
                    date_info = entry.name.split('-')
                    col_date = date(int(date_info[0]), int(date_info[1]), int(date_info[2]))
                    book = openpyxl.load_workbook(entry.name + os.sep + 'fund.xlsx')
                    sheet = book.active
                    r = 1
                    while True:
                        cell = sheet.cell(row=r, column=1)
                        r = r + 1
                        if cell.value is None:
                            break
                        if cell.value == fund_code:
                            cell = sheet.cell(row=r, column=6)
                            if cell.value is None:
                                break
                            number_of_shares = int(cell.value.replace(',', ''))
                            break
                    book = None

                    book = openpyxl.load_workbook(entry.name + os.sep + fund_code + '.xlsx')
                    sheet = book.active
                    cell = sheet.cell(row=2, column=1)
                    date_info = cell.value.split('-')
                    date_time = date(int(date_info[0]), int(date_info[1]), int(date_info[2]))
                    average_nav = float(sheet.cell(row=2, column=4).value)
                    if number_of_shares is None or date_time is None or average_nav is None:
                        continue
                    book = None
                    fund_item = {
                        'number_of_shares': number_of_shares,
                        'date_time': date_time,
                        'average_nav': average_nav,
                        'col_date': col_date
                    }

                    if fund_code not in full_new_datas:
                        full_new_datas[fund_code] = [fund_item]
                    else:
                        exists_element = False
                        for i in range(len(full_new_datas[fund_code])):
                            if full_new_datas[fund_code][i]['date_time'] == date_time:
                                exists_element = True
                                if full_new_datas[fund_code][i]['col_date'] < col_date:
                                    full_new_datas[fund_code][i] = fund_item
                        if not exists_element:
                            full_new_datas[fund_code].append(fund_item)
            if fund_code in full_new_datas:
                full_new_datas[fund_code].sort(key=lambda e: e['date_time'])
    with open(dir_name + os.sep + 'fund_sort_average_nav.csv', 'w', newline = '') as fp:
        write = csv.writer(fp)
        for k in full_new_datas.keys():
            item = [k]
            for e in full_new_datas[k]:
                item.append(e['average_nav'])
            write.writerow(item)

if __name__ == '__main__':
    dir_name = 'reports'
    if not Path(dir_name).is_dir():
        os.mkdir(dir_name)
    build_csv_file(dir_name)
